﻿var BasketClient = new function () {
    var addToBasketURL;
    var removeTermURL;
    this.SetAddToBasketUrl = function (url) {
        addToBasketURL = url;
    };

    this.SetRemoveItemUrl = function (url) {
        removeTermURL = url;
    };

    this.AddToBasket = function (id) {
        $.ajax({
            type: 'POST',
            url: addToBasketURL,
            dataType: 'json',
            data: { termId: id },
            success: function (response) {
                if (!response.IsError) {
                    $('#basket-qty').html(response.Data.Count);
                    BasketClient.RefreshTopBasket(true);
                    //alert("Should show shopping basket ");
                } else {
                    Feedback.ShowError(response.Object);
                    $('#topcontrol').click();
                }
            },
            error: function(data) {
                window.location.href = "/Account/Login";
            }
        });
    };

    this.RemoveItemFromBasket = function (id) {
        $.ajax({
            type: 'POST',
            url: removeTermURL,
            dataType: 'json',
            data: { id: id },
            success: function (response) {
                if (!response.IsError) {
                    $('#basket-qty').html(response.Data.Count);
                    $('#' + id).remove();
                    $('#totalPrice').html(response.Data.TotalPrice);
                    BasketClient.RefreshTopBasket(false);
                    var items = $.trim($("#checkoutlist > tbody").html());
                    if (items == "") {
                        $("#btnProcessCheckout").attr("disabled", "disabled");
                    }
                } else {
                    Feedback.ShowError(response.Object);

                }
            },
            error: function () { }
        });
    };

    this.RefreshTopBasket = function (showShoppingCart) {
        $.ajax({
            url: "/Basket/GetUserBasket",
            cache: false,
            dataType: "html",
            success: function (data) {
                $("#topShoppingCart").html(data);
                if (showShoppingCart) {
                    $("#topShoppingCart").show();
                    $("#topShoppingCart").fadeOut(2400);
                }
            }
        });
    };
};


